package com.brave.tools.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.brave.base.BaseController;
import com.brave.base.RedisKit;
import com.brave.config.AliSMSConfiguration;
import com.brave.utils.GenerateVerifyCodeKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(value = "工具通用部分接口", tags = "工具部分接口", description = "工具部分接口")
@RestController
@RequestMapping("/v1/tools")
public class ToolsController extends BaseController
{
    @Autowired
    private AliSMSConfiguration configuration;
    @Autowired
    private RedisKit redisKit;
    
    
    
    @ApiOperation(value = "工具-发送验证短信")
    @ApiImplicitParam(name = "phone", value = "手机号码", required = true, dataType = "string", paramType = "query")
    @GetMapping(value = "/sendSMS", produces = "application/json")
    public String sendSMS(@RequestParam("phone") String phone)
    {
        Map<String, Object> resultMap = new HashMap<>(2);
        try
        {
            String verifyCode = redisKit.getValue(phone);
            if(null != verifyCode && !"".equals(verifyCode))
            {
                resultMap.put("verifyCode", "已经发送过验证码");
                return success(resultMap);
            }else
            {
                verifyCode = GenerateVerifyCodeKit.generate();
                redisKit.saveTempValue(phone, verifyCode, TimeUnit.MINUTES, 5);
                SendSmsResponse response = configuration.sendSms(phone, verifyCode);
                resultMap.put("verifyCode", verifyCode);
                return success(resultMap);
            }
        }catch(ClientException ce)
        {
            ce.printStackTrace();
            resultMap.put("exception", ce.getErrMsg());
            return customResultMsg(500, "服务端异常", resultMap);
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
